import { Controller } from 'egg';

export default class BusinessInfo extends Controller {
  public async create() {
    const { ctx } = this;
    const { name, avatar, phone, introduction, discount, address, weight, cate } = ctx.request.body;
    try {
      await (new ctx.model.BusinessInfo({
        name,
        avatar,
        phone,
        introduction,
        discount,
        address,
        weight,
        cate,
      })).save();
      const data = await ctx.model.BusinessInfo.find({}).sort({ weight: 'desc' });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -2, message: e };
    }
  }
  public async update(){
    const { ctx } = this;
    const { id } = ctx.params;
    const { name, avatar, phone, introduction, discount, address, weight, cate } = ctx.request.body;
    try {
      await ctx.model.BusinessInfo.updateOne({_id: id}, {
        name,
        avatar,
        phone,
        introduction,
        discount,
        address,
        weight,
        cate,
      });
      const data = await ctx.model.BusinessInfo.find({}).sort({ weight: 'desc' });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -2, message: e };
    }
  }
  public async getList() {
    const { ctx } = this;
    const data = await ctx.model.BusinessInfo.find({}).sort({ weight: 'desc' });
    ctx.body = data;
  }
  public async getListByCate() {
    const { ctx } = this;
    try {
      const cate = ctx.params.id;
      const data = await ctx.model.BusinessInfo.find({ cate }).sort({ weight: 'desc' });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -1, message: '数据查询错误' };
    }
  }
  public async delete() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      await ctx.model.BusinessInfo.deleteOne({ _id: id });
      const allBusinessCate =
        await ctx.model.BusinessInfo.find({}).sort({ weight: 'desc' });
      ctx.body = allBusinessCate;
    } catch (e) {
      ctx.body = { status: -1, message: '删除失败' };
    }
  }

  public async baiduMap() {
    const { ctx } = this;
    const res = await ctx.curl('http://api.map.baidu.com/geocoder/v2/?address=' + ctx.params.address +'&output=json&ak=' + '9GrtytzKgTcfIeaAacATvjpVxBd8v792',{
      dataType: 'json',
    });
    ctx.body = res;
  }
}
